#include <REGX52.H>
sbit RS=P2^6;
sbit RW=P2^5;
sbit E=P2^7;
#define LCD_DataPort P0//P0~7是并行数据

void Delay1ms(void)	//@11.0592MHz
{
	unsigned char data i, j;

	i = 2;
	j = 199;
	do
	{
		while (--j);
	} while (--i);
}

//首先决定向它写（指令/数据）或读
void LCD_WriteCommand(unsigned char Command)
{
	RS=0;
	RW=0;
	LCD_DataPort=Command;
	E=1;
	Delay1ms();//指令有一个执行时间，高低电平不能给的太快，可以参考手册
	E=0;
	Delay1ms();
}

void LCD_WriteData(unsigned char Data)
{
	RS=1;
	RW=0;
	LCD_DataPort=Data;
	E=1;
	Delay1ms();
	E=0;
	Delay1ms();
}

void LCD_Init(void)
{
	LCD_WriteCommand(0x38);
	LCD_WriteCommand(0x0c);
	LCD_WriteCommand(0x06);
	LCD_WriteCommand(0x01);
}

//设置光标位置
void LCD_AC(unsigned char Line,unsigned char Column)
{
	if(Line==1)
	{
		LCD_WriteCommand(0x80|Column-1);
	}
	else
	{
		LCD_WriteCommand(0x80|Column-1+0x40);
	}
}

void LCD_ShowChar(unsigned char Line,unsigned char Column,unsigned char Char)
{
	LCD_AC(Line,Column);
	LCD_WriteData(Char);
}

//字符串相当于一个（字符）数组，且数组传参时只能传首地址
void LCD_ShowString(unsigned char Line,unsigned char Column,unsigned char *String)
{
	unsigned char i;
	LCD_AC(Line,Column);
	for(i=0;String[i]!='\0';i++)//遇到'\0'就截止，且不会打印'\0'
	{
		LCD_WriteData(String[i]);
	}
}

unsigned char LCD_Pow(unsigned char x,unsigned char y)
{
	unsigned char i;
	int ret=1;
	for(i=0;i<y;i++)
	{
		ret*=x;//不断乘以自身
	}
	return ret;
}

void LCD_ShowNum(unsigned char Line,unsigned char Column,unsigned int Number,unsigned char Length)
{
	unsigned char i;
	LCD_AC(Line,Column);
	for(i=Length;i>0;i--)
	{
		LCD_WriteData('0'+Number/LCD_Pow(10,i-1)%10);//要将数字转换成ASCII表值--+'0'或者+0x30!!!
	}
}

void LCD_ShowSigndNum(unsigned char Line,unsigned char Column,int ,unsigned char Length)
{
	unsigned char i;
	unsigned int Number1;//防止Number为负值时，-Number超过int范围
	LCD_AC(Line,Column);
	
	if(Number>=0)
	{
		LCD_WriteData('+');
		Number1=Number;
	}
	else
	{
		LCD_WriteData('-');
		Number1=-Number;
	}
	for(i=Length;i>0;i--)
	{
		LCD_WriteData('0'+Number1/LCD_Pow(10,i-1)%10);//要将数字转换成ASCII表值--+'0'或者+0x30!!!
	}
}

void LCD_ShowHexNum(unsigned char Line,unsigned char Column,unsigned int Number,unsigned char Length)
{
	unsigned char i;
	unsigned char SingleNumber;
	LCD_AC(Line,Column);
	for(i=Length;i>0;i--)
	{
		SingleNumber=Number/LCD_Pow(16,i-1)%16;//为了提取出16进制数的每一位
		if(SingleNumber<10)LCD_WriteData('0'+SingleNumber);
		else LCD_WriteData('A'+SingleNumber-10);
	}
}

void LCD_ShowBinNum(unsigned char Line,unsigned char Column,unsigned int Number,unsigned char Length)
{
	unsigned char i;
	LCD_AC(Line,Column);
	for(i=Length;i>0;i--)
	{
		LCD_WriteData('0'+Number/LCD_Pow(2,i-1)%2);//为了提取出2进制数的每一位
	}
}